package colaborativo.ondefica;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.osmdroid.api.IMapController;
import org.osmdroid.bonuspack.overlays.Marker;
import org.osmdroid.bonuspack.overlays.Marker.OnMarkerDragListener;
import org.osmdroid.bonuspack.overlays.MarkerInfoWindow;
import org.osmdroid.bonuspack.overlays.Polyline;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.MapView.Projection;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;

public class openMap extends Activity{
	MapView map;
	Projection pr1, pr2;
	
	protected void onCreate(Bundle savedInstanceState) {
		//Introduction
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_openmap);
		map = (MapView) findViewById(R.id.map);
		map.setTileSource(TileSourceFactory.MAPNIK);
		map.setBuiltInZoomControls(true);
		map.setMultiTouchControls(true);
		
		GeoPoint startPoint = new GeoPoint(-3.08923,-59.96453);
		IMapController mapController = map.getController();
		mapController.setZoom(18);
		mapController.setCenter(startPoint);				
//		plot_points();
		new MyAsyncTask().execute("teste");
		map.setOnTouchListener(new OnTouchListener() {			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				Boolean control = true;				
				switch (event.getAction() & MotionEvent.ACTION_MASK) {
				    case MotionEvent.ACTION_DOWN:						    	
				        v.setPressed(true);	
				        control = false;
				        break;
				    case MotionEvent.ACTION_UP:
				    	control = false;
				    	break;
				    case MotionEvent.ACTION_OUTSIDE:
				        v.setPressed(false);
				        new MyAsyncTask().execute("teste");
				        // Codigo se o tempo pressionando				        				        
				        break;
				    case MotionEvent.ACTION_MOVE:				    	
				    	v.setPressed(false);
				    	control = false;
				        break;
				    case MotionEvent.ACTION_POINTER_UP:
				        break;					   
			    }
				
				return control;
			}
		});		
		new MyAsyncTask().execute("teste");
	}
	
	//0. Using the Marker overlay
		class OnMarkerDragListenerDrawer implements OnMarkerDragListener {			
			ArrayList<GeoPoint> mTrace = new ArrayList<GeoPoint>(200);
			@Override public void onMarkerDrag(Marker marker) {				
				mTrace.add(marker.getPosition());				
			}
			@Override public void onMarkerDragEnd(Marker marker) {				
				Polyline p = new Polyline(map.getContext());
				p.setColor(0xAA0000FF);
				p.setWidth(2.0f);
				p.setPoints(mTrace);				
				map.getOverlays().add(p);
				map.invalidate();		
			}
			@Override public void onMarkerDragStart(Marker marker) {
				mTrace.add(marker.getPosition());				
			}
		}
		
		private void plot_points(JSONArray pontos){				
    		Drawable poiIcon = getResources().getDrawable(R.drawable.marker_poi_default);
    		if(pontos!=null){
	    		for(int i = 0;i<pontos.length();i++){
	    			try{
	    				Marker pto = new Marker(map);
	    				pto.setPosition(new GeoPoint( pontos.getJSONObject(i).getInt("latitute"), pontos.getJSONObject(i).getInt("longitude")));
	    				pto.setAnchor(Marker.ANCHOR_CENTER, 1.0f);
	    				pto.setIcon(poiIcon);
	    				pto.setInfoWindow(new CustomInfoWindow(map, pontos.getJSONObject(i).getInt("idLocal")));
	    				pto.setOnMarkerDragListener(new OnMarkerDragListenerDrawer());	    				
	    				Log.d("opMap.ResultadosMarcadores", pontos.getJSONObject(i).getString("nomeLocal"));
	    				pto.setTitle(pontos.getJSONObject(i).getString("nomeLocal"));
	    				map.getOverlays().add(pto);
	    			}catch(JSONException e){				
	    			}			
	    		}
	    		map.invalidate();
    		}
    	}
    	
		//7. Customizing the bubble behaviour
		class CustomInfoWindow extends MarkerInfoWindow {
			
			public CustomInfoWindow(MapView mapView, int localID) {
				super(R.layout.bonuspack_bubble, mapView);
				
				Button btn = (Button)(mView.findViewById(R.id.bubble_moreinfo));
				btn.setOnClickListener(new View.OnClickListener() {
				    public void onClick(View view) {
//				        if (mSelectedPoi.mUrl != null){
//				            Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(mSelectedPoi.mUrl));
//				            view.getContext().startActivity(myIntent);
//				        } else {
//				        	Toast.makeText(view.getContext(), "Button clicked", Toast.LENGTH_LONG).show();
//				        }
				    }
				});
			}
			@Override public void onOpen(Object item){
				super.onOpen(item);
				mView.findViewById(R.id.bubble_moreinfo).setVisibility(View.VISIBLE);
				
				//8. put thumbnail image in bubble, fetching the thumbnail in background:
//				if (mSelectedPoi.mThumbnailPath != null){
//					ImageView imageView = (ImageView)mView.findViewById(R.id.bubble_image);
//					mSelectedPoi.fetchThumbnailOnThread(imageView);
//				}
			}	
		}
		
	    private class MyAsyncTask extends AsyncTask<String, Integer, JSONArray>{
	    	JSONArray jSarr;
	    	
	        @Override
	        protected JSONArray doInBackground(String... params) {	        	
	        	Projection prj = map.getProjection();
	        	GeoPoint nordeste = (GeoPoint) prj.getNorthEast(), sudoeste = (GeoPoint) prj.getSouthWest(); 
	        	Log.d("Debug", nordeste.toString()+" / "+sudoeste.toString());
	        	
	    		String qry= "SELECT * FROM `geoPonto` WHERE `latitute`>= "+ sudoeste.getLatitudeE6() +" AND `latitute`<= "
	    				+ nordeste.getLatitudeE6() +" AND `longitude`>= "+sudoeste.getLongitudeE6()+" AND `longitude`<= "
	    				+nordeste.getLongitudeE6();
	    		Log.d("oM.pV.Query", qry);	    		
	    		return jSarr = DbConnection.consulta(qry);	    				        
	        }
	         
	        protected void onPostExecute(JSONArray result){
//		        Log.d("oM.pV.resultado", jSarr.toString());	    		
	        	
	        	Log.d("oM.pV.Result", "Acabou consulta");
	    			        	
	    		plot_points(result);    			  
	        }
	        protected void onProgressUpdate(Integer... progress){
//	        	progress(progress[0]);
	        }
	        
	        
	    }
}
